package com.cangxuan.backend.handler;

import com.cangxuan.backend.bean.Result;
import com.cangxuan.backend.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常捕获控制器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    HttpServletResponse response;
    @Autowired
    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    /**
     * 捕获ServiceException
     * @param exception
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public Object catchServiceException(ServiceException exception) {

        log.warn("捕获到异常了");
        log.warn(exception.getMessage());
        response.setStatus(exception.getStatus());
        return new Result(exception.getStatus(), exception.getMessage());

    }

}
